package org.finesys.commom.jackson.util;

import cn.hutool.extra.spring.SpringUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Json处理工具类
 */
public class JacksonUtil {

    /**
     * 获取对象
     */
    private static final ObjectMapper objectMapper = SpringUtil.getBean(ObjectMapper.class);

    @SneakyThrows
    public static String toJsonString(Object object) {
        return objectMapper.writeValueAsString(object);
    }

    @SneakyThrows
    public static byte[] toJsonByte(Object value) {
        return objectMapper.writeValueAsBytes(value);
    }

    @SneakyThrows
    public static <T> T parseObject(byte[] bytes, Class<T> tClass) {
        if (ObjectUtils.isEmpty(bytes)) {
            return null;
        }
        return objectMapper.readValue(bytes, tClass);
    }

    @SneakyThrows
    public static <T> T parseObject(String text, Class<T> tClass) {
        if (!StringUtils.hasLength(text)) {
            return null;
        }
        return objectMapper.readValue(text, tClass);
    }

    @SneakyThrows
    public static <T> T parseObject(String text, TypeReference<T> typeReference) {
        if (!StringUtils.hasLength(text)) {
            return null;
        }
        return objectMapper.readValue(text, typeReference);
    }

    @SneakyThrows
    public static <T> List<T> parseArray(String text, Class<T> tClass) {
        if (!StringUtils.hasLength(text)) {
            return new ArrayList<>();
        }
        return objectMapper.readValue(text, objectMapper.getTypeFactory().constructArrayType(tClass));
    }

    @SneakyThrows
    public static JsonNode parseTree(String text) {
        return objectMapper.readTree(text);
    }

    @SneakyThrows
    public static Map<String, Object> parseMap(String text) {
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(Map.class, String.class, Object.class);
        return objectMapper.readValue(text, javaType);
    }

}
